"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
exports.__esModule = true;
var THREE = require("three");
var GLTFLoader_1 = require("three/examples/jsm/loaders/GLTFLoader");
var vue_1 = require("vue");
var OrbitControls_js_1 = require("three/examples/jsm/controls/OrbitControls.js");
var ThreeUtil = /** @class */ (function () {
    /**
     *
     * @param {Object} obj
     * {
     *    camera:{
     *          x,y,z,fov,aspect,near,far
     *    },
     *    modelUrl:“”
     * }
     */
    function ThreeUtil(obj) {
        var _this = this;
        var _a, _b, _c, _d, _e, _f, _g;
        // 创建场景
        this.setScene = function () {
            ThreeUtil.scene = new THREE.Scene();
            ThreeUtil.renderer = new THREE.WebGLRenderer();
            ThreeUtil.renderer.setSize(innerWidth, innerHeight);
            document.body.appendChild(ThreeUtil.renderer.domElement);
        };
        // 创建相机
        this.setCamera = function () {
            var _a = _this.defaultMap, x = _a.x, y = _a.y, z = _a.z;
            ThreeUtil.camera = new THREE.PerspectiveCamera(_this.fov, _this.aspect, _this.near, _this.far);
            ThreeUtil.camera.position.set(x, y, z);
        };
        //加载模型
        this.loadFile = function (url) {
            return new Promise(function (resolve, reject) {
                _this.loader.load(url, function (gltf) {
                    resolve(gltf);
                }, function (_a) {
                    var loaded = _a.loaded, total = _a.total;
                    var load = Math.abs((loaded / total) * 100);
                    _this.loadingWidth.value = load;
                    if (load >= 100) {
                        setTimeout(function () {
                            _this.isLoading.value = false;
                        }, 1000);
                    }
                    console.log((loaded / total) * 100 + "% loaded");
                }, function (err) {
                    reject(err);
                });
            });
        };
        // 创建灯光
        this.setLight = function () {
            var directionalLight = new THREE.DirectionalLight(0xffffff, 0.9);
            directionalLight.position.set(-4, 8, 4);
            var hemisphereLight = new THREE.HemisphereLight(0xffffff, 0xffffff, 0.8);
            hemisphereLight.position.set(0, 8, 0);
            ThreeUtil.scene.add(directionalLight);
            ThreeUtil.scene.add(hemisphereLight);
            /**
             * 创建helper  辅助线
             */
            // const dhelper = new THREE.DirectionalLightHelper(directionalLight, 5, 0xff0000);
            // const hHelper = new THREE.HemisphereLightHelper(hemisphereLight, 5);
            // ThreeUtil.scene.add(dhelper);
            // ThreeUtil.scene.add(hHelper);
            // const light = new THREE.HemisphereLight(0xffffff, 0xDC143C, 1);
            // const helper2 = new THREE.HemisphereLightHelper(light, 5);
            // ThreeUtil.scene.add(helper2,light);
            // const gridHelper = new THREE.GridHelper(10, 10, 0xFFFFFF, 0xFFFFFF);
            // ThreeUtil.scene.add(gridHelper);
            // const helper = new THREE.PolarGridHelper(10, 16, 8, 64);
            // ThreeUtil.scene.add(helper);
        };
        // 模型控制器
        this.setControls = function () {
            ThreeUtil.controls = new OrbitControls_js_1.OrbitControls(ThreeUtil.camera, ThreeUtil.renderer.domElement);
            //   controls.maxPolarAngle = (0.9 * Math.PI) / 2;
            ThreeUtil.controls.enableZoom = true;
            ThreeUtil.controls.addEventListener("change", _this.render);
        };
        //返回坐标信息
        this.render = function () {
            _this.map.x = Number.parseInt(ThreeUtil.camera.position.x);
            _this.map.y = Number.parseInt(ThreeUtil.camera.position.y);
            _this.map.z = Number.parseInt(ThreeUtil.camera.position.z);
        };
        /**
         * 设置模型颜色
         * @param {string} color
         * @param {string} useKitField 使用模型的套件字段
         */
        this.setModelColor = function (color, useKitField) {
            var currentColor = new THREE.Color(color);
            ThreeUtil.scene.traverse(function (child) {
                // console.log('child.name：'+ child.name);
                if (child.isMesh) {
                    console.log(child.name); //当前的贴图套件字段
                    if (child.name.includes(useKitField)) {
                        // 设置贴图的颜色
                        child.material.color.set(currentColor);
                    }
                }
            });
        };
        /**
         * 是否自动转动
         * @param {Boolean} rotation 是否自动旋转
         * @param {Float} speed 旋转速度
         * @returns
         */
        this.autoRotation = function (rotation, speed) {
            if (rotation === void 0) { rotation = true; }
            if (speed === void 0) { speed = 2; }
            if (rotation == ThreeUtil.controls.autoRotate)
                return;
            ThreeUtil.controls.autoRotateSpeed = speed;
            ThreeUtil.controls.autoRotate = rotation;
        };
        // 循环场景 、相机、 位置更新
        this.loop = function () {
            requestAnimationFrame(_this.loop);
            ThreeUtil.renderer.render(ThreeUtil.scene, ThreeUtil.camera);
            ThreeUtil.controls.update();
        };
        // 初始化函数
        /**
         *
         * @param {*} obj 可以通过传true来不去初始化其对应的实例，因为你可以通过本类的实例去自定义它们
         */
        this.init = function (obj) { return __awaiter(_this, void 0, void 0, function () {
            var gltf;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.setScene();
                        !(obj === null || obj === void 0 ? void 0 : obj.setCamera) && this.setCamera();
                        !(obj === null || obj === void 0 ? void 0 : obj.setLight) && this.setLight();
                        !(obj === null || obj === void 0 ? void 0 : obj.setControls) && this.setControls();
                        return [4 /*yield*/, this.loadFile(this.modelUrl)];
                    case 1:
                        gltf = _a.sent();
                        ThreeUtil.scene.add(gltf.scene);
                        this.loop();
                        return [2 /*return*/];
                }
            });
        }); };
        this.defaultMap = {
            x: ((_a = obj === null || obj === void 0 ? void 0 : obj.camera) === null || _a === void 0 ? void 0 : _a.x) ? obj.camera.x : 0,
            y: ((_b = obj === null || obj === void 0 ? void 0 : obj.camera) === null || _b === void 0 ? void 0 : _b.y) ? obj.camera.y : 0,
            z: ((_c = obj === null || obj === void 0 ? void 0 : obj.camera) === null || _c === void 0 ? void 0 : _c.z) ? obj.camera.z : 2
        }; // 相机的默认坐标
        this.modelUrl = obj.modelUrl;
        this.map = (0, vue_1.reactive)(this.defaultMap); //把相机坐标设置成可观察对象
        var _h = (0, vue_1.toRefs)(this.map), x = _h.x, y = _h.y, z = _h.z; //输出坐标给模板使用
        this.x = x;
        this.y = y;
        this.z = z;
        /**
         * 相机相关配置，默认使用透视相机
         */
        this.fov = ((_d = obj === null || obj === void 0 ? void 0 : obj.camera) === null || _d === void 0 ? void 0 : _d.fov) ? obj.camera.fov : 75;
        this.aspect = ((_e = obj === null || obj === void 0 ? void 0 : obj.camera) === null || _e === void 0 ? void 0 : _e.aspect) ? obj.camera.aspect : innerWidth / innerHeight;
        this.near = ((_f = obj === null || obj === void 0 ? void 0 : obj.camera) === null || _f === void 0 ? void 0 : _f.near) ? obj.camera.near : 1;
        this.far = ((_g = obj === null || obj === void 0 ? void 0 : obj.camera) === null || _g === void 0 ? void 0 : _g.far) ? obj.camera.far : 10;
        this.loader = new GLTFLoader_1.GLTFLoader(); //引入模型的loader实例
        /**
         * 效果相关
         */
        this.isLoading = (0, vue_1.ref)(true); //是否显示loading  这个load模型监听的进度
        this.loadingWidth = (0, vue_1.ref)(0); // loading的进度
    }
    return ThreeUtil;
}());
exports["default"] = ThreeUtil;
